package com.brother.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.*;


//http://maps.google.com/staticmap?center=22.532717,114.038696&zoom=14&size=220x320&markers=22.532717,114.038696,red
public class StaticMap extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
//http://maps.google.com/staticmap?center=22.532717,114.038696&zoom=14&size=220x320&markers=22.532717,114.038696,red

		String size = req.getParameter("s");
		String zoom = req.getParameter("z");
		String center = req.getParameter("c");
		
		if(size == null){
			size = "480x320";
		}
		if(center == null){
			center="22.532717,114.138696";
		}
		if(zoom == null){
			zoom = "14";
		}
		//String httpUrl = "http://maps.google.com/staticmap?center=22.532717,114.038696&zoom=14&size=480x320&markers=22.532717,114.038696,red";
		String httpUrl = "http://maps.google.com/maps/api/staticmap?center="+center+"&zoom="+zoom+"&size="+size+"&maptype=roadmap&markers=color:red|label:S|"+center+"&sensor=false";
		
//		httpUrl = httpUrl.replaceFirst("center=[^&]*", "center="+center);
//		httpUrl = httpUrl.replaceFirst("zoom=[^&]*", "zoom="+zoom);
//		httpUrl = httpUrl.replaceFirst("size=[^&]*", "size="+size);
//		httpUrl = httpUrl.replaceFirst("markers=[^&]*", "markers="+center+",red");
		
		//  url format :http://host/map?c=22.532717,114.038696&z=14&s=220x320
		
		URL url = new URL(httpUrl);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		InputStream in = conn.getInputStream();
		
		resp.reset();
		resp.setContentType("image/gif");
		
		OutputStream out = resp.getOutputStream();
		
		int read = -1;
		byte[] buf = new byte[1024];
		while((read = in.read(buf, 0, 1024)) != -1){
			out.write(buf, 0, read);
		}
		out.close();
		in.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req,resp);
	}

	
	
}
